package com.xuyn.alipay.controller;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.xuyn.alipay.config.AlipayProperties;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class AlipayController {
    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private AlipayProperties aliPayProperties;

    @Autowired
    private HttpServletResponse response;

    @PostMapping("alipay/page/gotoPayPage")
    public void gotoPayPage() throws AlipayApiException, IOException {
        // 订单模型
        String productCode = "FAST_INSTANT_TRADE_PAY";
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(UUID.randomUUID().toString());
        model.setSubject("掏心会员12个月");
        model.setTotalAmount("388");
        model.setBody("掏心会员12个月，优惠价￥388元");
        model.setProductCode(productCode);

        AlipayTradePagePayRequest pagePayRequest = new AlipayTradePagePayRequest();
        pagePayRequest.setReturnUrl(aliPayProperties.getReturnUrl());
        pagePayRequest.setNotifyUrl(aliPayProperties.getNotifyUrl());
        pagePayRequest.setBizModel(model);

        // 调用SDK生成表单, 并直接将完整的表单html输出到页面
        String form = alipayClient.pageExecute(pagePayRequest).getBody();
        response.setContentType("text/html;charset=" + aliPayProperties.getCharset());
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }


//    @PostMapping("/alipay/f2fpay/precreate")
//    public void precreate() throws Exception {
//        AlipayTradePayRequest request = new AlipayTradePayRequest();
//        AlipayTradePayModel model = new AlipayTradePayModel();
//        request.setBizModel(model);
//
//        model.setOutTradeNo(System.currentTimeMillis() + "");
//        model.setSubject("Iphone6 16G");
//        model.setTotalAmount("0.01");
//        model.setAuthCode("xxxxx");//沙箱钱包中的付款码
//        model.setScene("bar_code");
//
//        AlipayTradePayResponse response = null;
//        try {
//            response = alipayClient.execute(request);
//            System.out.println(response.getBody());
//            System.out.println(response.getTradeNo());
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//    }
}
